# -*- coding:utf-8 -*-
# @FileName  :main.py
# @Time      :2024/7/4 11:45
# @Author    :lin
import sys

from read_excel import *
import time
import requests
import json
import datetime
import pandas as pd

API_KEY = "ioZb4KVL5KkChXOrH7nXV5A5"
SECRET_KEY = "kPHgfUMH2kbLgDMsU1YYN06xb9KLER0D"


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


def get_token():
    """读取外部文件，判断天数是否需要重新获取token"""

    if getattr(sys, 'frozen', None):
        basedir = sys._MEIPASS  # 打包后用的这个路径
    else:
        basedir = os.path.dirname(__file__)  # 直接运行的时候用的这个

    with open(os.path.join(basedir, 'token.txt'), "r+") as f:
        first_line = f.readline().strip()
        second_line = f.readline().strip()
        doing_date = datetime.datetime.strptime(first_line, "%Y-%m-%d")
        now_date = datetime.datetime.now()
        if (now_date - doing_date).days > 10:
            f.seek(0)
            f.write(now_date.strftime("%Y-%m-%d") + "\n" + str(get_access_token()) + "\n")
            print("token已过期，已重新获取token")
            return get_access_token()
        else:
            return second_line


token = get_token()


def trans(_from, _to, _q):
    # url = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + get_access_token()
    url = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + token

    payload = json.dumps({
        "from": _from,
        "to": _to,
        "q": _q
    })
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    # print(response.text)
    return response.json()


def main(_path="1.xlsx", _pathTranslate="2.xlsx", formData=None):
    if formData:
        body_dict = formData
    else:
        body_dict = get_dict(_path)

    data = {_item: [] for _item in body_dict["language"]}

    _form = body_dict["language"][0]
    data[_form] = body_dict["text"]

    for _to in body_dict["language"][1:]:
        _text = "\n".join(body_dict["text"])
        time.sleep(0.5)
        _trans = trans(_form, _to, _text)
        value = []
        for item in _trans["result"]["trans_result"]:
            value.append(item["dst"])
        print("to", _to, "translate success!")
        data[_to] = value

    if _path != "1.xlsx" or formData:
        df = [body_dict["language"]]
        for i in range(len(body_dict["text"])):
            df.append([data[item][i] for item in body_dict["language"]])
        return {"data": df}
    pd.DataFrame(data).to_excel(pathTranslate, index=False)

# if __name__ == '__main__':
#     start_time = time.time()
#     main()
#     end_time = time.time()
#
#     print("程序运行时间：", end_time - start_time)
#     print("翻译完成，请查看2.xlsx文件，此窗口将在五秒后关闭")
#     time.sleep(5)
